<?php
//部门
namespace app\crm\controller;

use app\crm\model\Sys;
use think\Config;
use think\Db;
use think\Request;
use think\Exception;
use app\crm\model\Department as DepartmentModel;
use app\crm\model\Staff as StaffModel;
use app\crm\model\Cusarea as CusareaModel;
class Communitytree extends \CrmController
{
    static private $DiDuiBumen = [];
    public function base64EncodeImage ($image_file) {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }
    public function testdownload(Request $request){
       
            $url = $request->get('url');
            if(!empty($url)){
              $url=  ROOT_PATH."public".DS."accessory".DS."20190613".DS."41c49caf9f021d8cfa0566885c5ec3a3.jpg";
              return $this->base64EncodeImage($url);

            }
        
    }
    public function gettag(){
       
            $StaffModel = new \app\crm\model\Staff();
          
           
            $data=db("tag")->field("tag_id,tag_name")->select();
            $params=[];
            foreach ($data as $k => $v) {
                # code...
                $tmp["client_tag_id"]=$v["tag_id"];
                $tmp["tag_name"]=$v["tag_name"];
                $tmp["children"]=[];
                $tmp["is_show"]=false;
                $tmp["parent_id"]=0;
                $params[]=$tmp;
            }
            $this->successTerminate($params);
       
    }
    public function getclient(){
       
            $StaffModel = new \app\crm\model\Staff();
          
           
            $data=db("client")->where("is_del=0")->field("client_id,client_name")->select();
            $params=[];
            foreach ($data as $k => $v) {
                # code...
                $tmp["client_id"]=$v["client_id"];
                $tmp["client_name"]=$v["client_name"];
                $tmp["children"]=[];
                $tmp["is_show"]=false;
                $tmp["parent_id"]=0;
                $params[]=$tmp;
            }
            $this->successTerminate($params);
       
    }
     public function getcate(){
       
            $StaffModel = new \app\crm\model\Staff();
          
           
            $data=db("client_category")->field("client_cate_id,client_cate_name")->select();
            $params=[];
            foreach ($data as $k => $v) {
                # code...
                $tmp["client_cate_id"]=$v["client_cate_id"];
                $tmp["client_cate_name"]=$v["client_cate_name"];
                $tmp["children"]=[];
                $tmp["is_show"]=false;
                $tmp["parent_id"]=0;
                $params[]=$tmp;
            }
            $this->successTerminate($params);
       
    }
    public function deleteclassify(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            
            $classify_id=$params["classify_id"];
           
            db("crm_subregion_classify")->where(["classify_id"=>$classify_id])->delete();
            $this->successTerminate($params);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function addClassify(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $subregion_id=$params["subregion_id"];
            $classify_name=trim($params["classify_name"]);
            $type=$params["type"];
            if(!$classify_name){
                \exception("分类名不能为空");
            }
            $count=db("crm_subregion_classify")->where(["subregion_id"=>$subregion_id])->count();
            if($count>=6){
                \exception("社区内分类最多6个");
            }
            $has=db("crm_subregion_classify")->where(["subregion_id"=>$subregion_id,"classify_name"=>$classify_name])->find();
            if($has){
                \exception("社区内已存在分类".$classify_name);
            }

            $data["classify_name"]=$classify_name;
            $data["subregion_id"]=$subregion_id;
            if($type=="全部可以选择"){
                $data["is_access"]=0;
            }else if($type=="仅员工可以选择")
                $data["is_access"]=1;
            else
                $data["is_access"]=2;
            db("crm_subregion_classify")->insert($data);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function updateClassify(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $subregion_id=$params["subregion_id"];
            $classify_id=$params["classify_id"];
            $classify_name=trim($params["classify_name"]);
            $type=$params["type"];
            if(!$classify_name){
                \exception("分类名不能为空");
            }
        
            $has=db("crm_subregion_classify")->where("classify_name='{$classify_name}' and subregion_id='{$subregion_id}' and classify_id<>$classify_id")->find();
            if($has){
                \exception("社区内已存在分类".$classify_name);
            }

            $data["classify_name"]=$classify_name;
           
            if($type=="全部可以选择"){
                $data["is_access"]=0;
            }else if($type=="仅员工可以选择")
                $data["is_access"]=1;
            else
                $data["is_access"]=2;
            db("crm_subregion_classify")->where(["classify_id"=>$classify_id])->update($data);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function savedownstaff(Request $request){
        try{
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->post());  
            $subregion_id=$params["subregion_id"];
            $staff_list=explode(',',$params["ustr"]);
            $ccstr=explode(',',$params["ccstr"]);
            $ctstr=explode(',',$params["ctstr"]);
            $cstr=explode(',',$params["cstr"]);
            $st=[];
            foreach ($staff_list as $k => $v) {
                # code...
                $tmp["downstream_id"]=$v;
                $tmp["subregion_id"]=$subregion_id;
                $st[]=$tmp;
            }
            $de=[];
            foreach ($ccstr as $k => $v) {
                # code...
                if($v){
                    $tmps["obj_id"]=$v;
                    $tmps["subregion_id"]=$subregion_id;
                    $tmps["type"]=0;
                    $de[]=$tmps;
                }
                
            }
            foreach ($ctstr as $k => $v) {
                # code...
                if($v){
                    $tmps["obj_id"]=$v;
                    $tmps["subregion_id"]=$subregion_id;
                    $tmps["type"]=1;
                    $de[]=$tmps;
                }
                
            }
            foreach ($cstr as $k => $v) {
                # code...
                if($v){
                    $tmps["obj_id"]=$v;
                    $tmps["subregion_id"]=$subregion_id;
                    $tmps["type"]=2;
                    $de[]=$tmps;
                }
                
            }
            db("crm_subregion_visible_downstream")->where(["subregion_id"=>$subregion_id])->delete();
            db("crm_subregion_visible_downtag")->where(["subregion_id"=>$subregion_id])->delete();
            if($st){
                db("crm_subregion_visible_downstream")->insertAll($st);
            }
            if($de){
                db("crm_subregion_visible_downtag")->insertAll($de);
            }
            $data=$this->getalldown($subregion_id);
            $this->successTerminate($data);
        } catch (Exception $e) {
           
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function saveIssueStaff(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->post());
            $subregion_id=$params["subregion_id"];
            $staff_list=explode(',',$params["staff_list"]);
            $depart_list=explode(',',$params["depart_list"]);
            $st=[];
            foreach ($staff_list as $k => $v) {
                # code...
                $tmp["staff_id"]=$v;
                $tmp["subregion_id"]=$subregion_id;
                $st[]=$tmp;
            }
            $de=[];
            foreach ($depart_list as $k => $v) {
                # code...
                $tmps["department_id"]=$v;
                $tmps["subregion_id"]=$subregion_id;
                $de[]=$tmps;
            }
           
            
            db("crm_subregion_issue_department")->where(["subregion_id"=>$subregion_id])->delete();
            db("crm_subregion_issue_staff")->where(["subregion_id"=>$subregion_id])->delete();
            if($st){
                db("crm_subregion_issue_staff")->insertAll($st);
            }
            if($de){
                db("crm_subregion_issue_department")->insertAll($de);
            }
                   
            
            $this->successTerminate($params);
        } catch (Exception $e) {
           
            $this->serverErrorTerminate($e->getMessage());
        }

    }
    public function saveVisableStaff(Request $request){
        
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->post());
            $subregion_id=$params["subregion_id"];
            $staff_list=explode(',',$params["staff_list"]);
            $depart_list=explode(',',$params["depart_list"]);
            $st=[];
            foreach ($staff_list as $k => $v) {
                # code...
                $tmp["staff_id"]=$v;
                $tmp["subregion_id"]=$subregion_id;
                $st[]=$tmp;
            }
            $de=[];
            foreach ($depart_list as $k => $v) {
                # code...
                $tmps["department_id"]=$v;
                $tmps["subregion_id"]=$subregion_id;
                $de[]=$tmps;
            }
           
            
            db("crm_subregion_visible_department")->where(["subregion_id"=>$subregion_id])->delete();
            db("crm_subregion_visible_staff")->where(["subregion_id"=>$subregion_id])->delete();
            if($st){
                db("crm_subregion_visible_staff")->insertAll($st);
            }
            if($de){
                db("crm_subregion_visible_department")->insertAll($de);
            }
                   
            
            $this->successTerminate($params);
        } catch (Exception $e) {
           
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    
    public function getsys(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $subregion_id=$params["subregion_id"];
            $data=db("crm_subregion_sys")->where("subregion_id=$subregion_id")->find();
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function changesys(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $subregion_id=$params["subregion_id"];
            $title=$params["title"];
            $state=$params["state"];

            $data=db("crm_subregion_sys")->where("subregion_id=$subregion_id")->update([$title=>$state]);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function setdownaccess(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $subregion_id=$params["subregion_id"];
            $state=$params["state"];
            db("crm_subregion_sys")->where("subregion_id=$subregion_id")->update(["is_downstream_access"=>$state]);
            $this->successTerminate($params);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function setdownaccess2(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $subregion_id=$params["subregion_id"];
            $state=$params["state"];
            db("crm_subregion_sys")->where("subregion_id=$subregion_id")->update(["downstream_scope"=>$state]);
            $this->successTerminate($params);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function savelinkman(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->post());
            $subregion_id=$params["subregion_id"];
            //修改设置
            $rulestr=explode(',',$params["rule_list"]);
            if(in_array("手机",$rulestr)){
                $update["linkman_phone"]=1;
            }else{
                $update["linkman_phone"]=0;
            }
            if(in_array("工作邮箱",$rulestr)){
                $update["linkman_email"]=1;
            }else{
                $update["linkman_email"]=0;
            }
            if(in_array("工作座机",$rulestr)){
                $update["linkman_telephone"]=1;
            }else{
                $update["linkman_telephone"]=0;
            }
            if(in_array("微信号",$rulestr)){
                $update["linkman_wechat"]=1;
            }else{
                $update["linkman_wechat"]=0;
            }
            if(in_array("QQ号",$rulestr)){
                $update["linkman_qq"]=1;
            }else{
                $update["linkman_qq"]=0;
            }
            db("crm_subregion_sys")->where("subregion_id=$subregion_id")->update($update);
            $staff_list=explode(',',$params["staff_list"]);
            $depart_list=explode(',',$params["depart_list"]);
            $st=[];
            foreach ($staff_list as $k => $v) {
                # code...
                $tmp["staff_id"]=$v;
                $tmp["subregion_id"]=$subregion_id;
                $st[]=$tmp;
            }
            $de=[];
            foreach ($depart_list as $k => $v) {
                # code...
                $tmps["department_id"]=$v;
                $tmps["subregion_id"]=$subregion_id;
                $de[]=$tmps;
            }
           
            
            db("crm_subregion_linkman_department")->where(["subregion_id"=>$subregion_id])->delete();
            db("crm_subregion_linkman_staff")->where(["subregion_id"=>$subregion_id])->delete();
            if($st){
                db("crm_subregion_linkman_staff")->insertAll($st);
            }
            if($de){
                db("crm_subregion_linkman_department")->insertAll($de);
            }
            $this->successTerminate($params);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function savedownman(Request $request){
        try {
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->post());
            $subregion_id=$params["subregion_id"];
           
            $staff_list=explode(',',$params["staff_list"]);
            $depart_list=explode(',',$params["depart_list"]);
            $st=[];
            foreach ($staff_list as $k => $v) {
                # code...
                $tmp["staff_id"]=$v;
                $tmp["subregion_id"]=$subregion_id;
                $st[]=$tmp;
            }
            $de=[];
            foreach ($depart_list as $k => $v) {
                # code...
                $tmps["department_id"]=$v;
                $tmps["subregion_id"]=$subregion_id;
                $de[]=$tmps;
            }
           
            
            db("crm_subregion_remind_department")->where(["subregion_id"=>$subregion_id])->delete();
            db("crm_subregion_remind_staff")->where(["subregion_id"=>$subregion_id])->delete();
            if($st){
                db("crm_subregion_remind_staff")->insertAll($st);
            }
            if($de){
                db("crm_subregion_remind_department")->insertAll($de);
            }
            $this->successTerminate($params);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function getlinkman(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        $params = delToken($request->get());
        $subregion_id=$params["class_id"];
        $sys=db("crm_subregion_sys")->where("subregion_id=$subregion_id")->find();
        $rule=[];
        if($sys["linkman_phone"]){
            $rule[]="手机";
        }
        if($sys["linkman_email"]){
            $rule[]="工作邮箱";
        }
        if($sys["linkman_telephone"]){
            $rule[]="工作座机";
        }
        if($sys["linkman_wechat"]){
            $rule[]="微信号";
        }
        if($sys["linkman_qq"]){
            $rule[]="QQ号";
        }
        $data["rule"]=$rule;
        $data["user"]=db("crm_subregion_linkman_staff")->alias("a")
        ->join("sh_crm_staff b","a.staff_id=b.staff_id")
        ->where("a.subregion_id=$subregion_id")
        ->field("a.staff_id,b.staff_name,head_img")
        ->select();
        $data["depart"]=db("crm_subregion_linkman_department")->alias("a")
        ->join("sh_crm_department b","a.department_id=b.department_id")
        ->where("a.subregion_id=$subregion_id")
        ->field("a.department_id,b.department_name")
        ->select();
        return $data;
    }
    public function getdownman(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        $params = delToken($request->get());
        $subregion_id=$params["class_id"];
       
        $data["user"]=db("crm_subregion_remind_staff")->alias("a")
        ->join("sh_crm_staff b","a.staff_id=b.staff_id")
        ->where("a.subregion_id=$subregion_id")
        ->field("a.staff_id,b.staff_name,head_img")
        ->select();
        $data["depart"]=db("crm_subregion_remind_department")->alias("a")
        ->join("sh_crm_department b","a.department_id=b.department_id")
        ->where("a.subregion_id=$subregion_id")
        ->field("a.department_id,b.department_name")
        ->select();
        return $data;
    }
    public function getdowntag(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        $params = delToken($request->get());
        $subregion_id=$params["class_id"];
        $data["subregion_name"]=db("crm_subregion")->where(["subregion_id"=>$subregion_id])->value("subregion_name");
        $data["user"]=db("crm_subregion_visible_downstream")->alias("a")
        ->join("sh_crm_staff b","a.downstream_id=b.staff_id")
        ->where("a.subregion_id=$subregion_id and b.is_del=0")
        ->field("b.staff_id,b.staff_name,head_img")
        ->select();
        //客户分类
        $data["client_type"]=db("crm_subregion_visible_downtag")->alias("a")
        ->join("sh_client_category b","a.obj_id=b.client_cate_id")
        ->where("a.subregion_id=$subregion_id and a.type=0")
        ->field("client_cate_id,client_cate_name")
        ->select();
      //  echo db("crm_subregion_visible_downtag")->getLastSql();die;
        //联系人标签
        $data["client_tag"]=db("crm_subregion_visible_downtag")->alias("a")
        ->join("sh_tag b","a.obj_id=b.tag_id")
        ->where("a.subregion_id=$subregion_id and a.type=1")
        ->field("tag_id as client_tag_id,tag_name")
        ->select();
        //客户
        $data["client"]=db("crm_subregion_visible_downtag")->alias("a")
        ->join("sh_client b","a.obj_id=b.client_id")
        ->where("a.subregion_id=$subregion_id and b.is_del=0 and a.type=2")
        ->field("client_id,client_name")
        ->select();

        $data["linkmans"]=$this->getalldown($subregion_id);
        return $data;
    }
    public function getalldown($subregion_id){
        $StaffModel = new \app\crm\model\Staff();
         //客户分类
        $client_cate_id=db("crm_subregion_visible_downtag")->alias("a")
        ->join("sh_client_category b","a.obj_id=b.client_cate_id")
        ->where("a.subregion_id=$subregion_id and a.type=0")
        ->column("client_cate_id");
        if($client_cate_id){
            $ccid=implode(',',$client_cate_id);
            $client_id1=db("client_category_relevance")->where("client_cate_id in ($ccid)")->group("client_id")->column("client_id");
        }else{
            $client_id1=[];
        }
        $client_id2=db("crm_subregion_visible_downtag")->alias("a")
        ->join("sh_client b","a.obj_id=b.client_id")
        ->where("a.subregion_id=$subregion_id and b.is_del=0 and a.type=2")
        ->column("client_id");
        $client_ids=[];
        foreach ($client_id1 as $k => $v) {
            # code...
            if(!in_array($v,$client_ids)){
                $client_ids[]=$v;
            }
        }
        foreach ($client_id2 as $k => $v) {
            # code...
            if(!in_array($v,$client_ids)){
                $client_ids[]=$v;
            }
        }
        if($client_ids){
            $cids=implode(',',$client_ids);
            $staff_id1=db("client_staff_relevance")->where("client_id in ($cids)")->group("staff_id")->column("staff_id");
        }else{
            $staff_id1=[];
        }
        $client_tag=db("crm_subregion_visible_downtag")->alias("a")
        ->join("sh_tag b","a.obj_id=b.tag_id")
        ->where("a.subregion_id=$subregion_id and a.type=1")
        ->column("tag_id");
        if($client_tag){
            $ctid=implode(",",$client_tag);
            $staff_id2=db("crm_staff_tag_relevance")->where("tag_id in ($ctid)")->group("staff_id")->column("staff_id");
        }else{
            $staff_id2=[];
        }
        $staff_id3=db("crm_subregion_visible_downstream")->alias("a")
        ->join("sh_crm_staff b","a.downstream_id=b.staff_id")
        ->where("a.subregion_id=$subregion_id and b.is_del=0")->column("b.staff_id");
        $staff_ids=[];
        foreach ($staff_id1 as $k => $v) {
            # code...
            if(!in_array("'".$v."'",$staff_ids)){
                $staff_ids[]="'".$v."'";
            }
        }
        foreach ($staff_id2 as $k => $v) {
            # code...
             if(!in_array("'".$v."'",$staff_ids)){
                $staff_ids[]="'".$v."'";
            }
        }
        foreach ($staff_id3 as $k => $v) {
            # code...
             if(!in_array("'".$v."'",$staff_ids)){
                $staff_ids[]="'".$v."'";
            }
        }
        if($staff_ids){
            $stid=implode(',',$staff_ids);
            $data=db("crm_staff")->where("staff_id in ($stid) and is_downstream=0")->field("staff_id,staff_name,head_img as image,duty,is_login,attention_type,last_login")->select();
            foreach ($data as $k => $v) {
                # code...
                if($v["attention_type"])
                    $data[$k]["is_see"]="已关注";
                else
                    $data[$k]["is_see"]="未关注";
                if($v["last_login"])
                    $data[$k]["endTime"]=date("Y/m/d H:i");
                else
                    $data[$k]["endTime"]="";
                $data[$k]["type"]="下游成员";
                $data[$k]["company"]=db("client_staff_relevance")->alias("a")->join("sh_client b","a.client_id=b.client_id")->where("staff_id='{$v["staff_id"]}'")
                ->value("client_name");
            }
        }else{
            $data=[];
        }
        return $data;
        //print_r($client_ids);
    }
    public function changelog(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        $params = delToken($request->get());
        $staff_id=$params["staff_id"];
        db("crm_staff")->where(["staff_id"=>$staff_id])->update(["is_login"=>$params["is_login"]]);
    }
    public function getclassdet(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        $params = delToken($request->get());
        $subregion_id=$params["class_id"];
        $data["subregion_name"]=db("crm_subregion")->where(["subregion_id"=>$subregion_id])->value("subregion_name");
        $data["all"]=db("crm_dynamic")->alias("a")->join("sh_crm_staff b","a.staff_id=b.staff_id")->where("a.is_issue=0 and a.subregion_id=$subregion_id")->count();
        $data["emp"]=db("crm_dynamic")->alias("a")->join("sh_crm_staff b","a.staff_id=b.staff_id")->where("a.is_issue=0 and a.subregion_id=$subregion_id and b.is_downstream=1")->count();
        $data["down"]=db("crm_dynamic")->alias("a")->join("sh_crm_staff b","a.staff_id=b.staff_id")->where("a.is_issue=0 and a.subregion_id=$subregion_id and b.is_downstream=0")->count();
        $data["path"]=db("crm_dynamic")->alias("a")->join("sh_crm_dynamic_accessory b","a.dynamic_id=b.dynamic_id")->join("sh_crm_staff c","a.staff_id=c.staff_id")->where("a.is_issue=0 and a.subregion_id=$subregion_id")->count();
        $data["isdown"]=db("crm_subregion_sys")->where("subregion_id=$subregion_id")->value("is_downstream_access");
        if(!$data["isdown"])
            $data["isdown"]=0;
        $data["isdown2"]=db("crm_subregion_sys")->where("subregion_id=$subregion_id")->value("downstream_scope");
        if(!$data["isdown2"])
            $data["isdown2"]=0;
        $data["user"]=db("crm_subregion_visible_staff")->alias("a")
        ->join("sh_crm_staff b","a.staff_id=b.staff_id")
        ->where("a.subregion_id=$subregion_id and b.is_del=0")
        ->field("a.staff_id,b.staff_name,head_img")
        ->select();
        $data["depart"]=db("crm_subregion_visible_department")->alias("a")
        ->join("sh_crm_department b","a.department_id=b.department_id")
        ->where("a.subregion_id=$subregion_id")
        ->field("a.department_id,b.department_name")
        ->select();
        $data["tab"]=db("crm_subregion_classify")->where("subregion_id=$subregion_id")->select();
        foreach ($data["tab"] as $k => $v) {
            # code...
            if($data["tab"][$k]["is_access"]==0){
                $data["tab"][$k]["type"]="全部可以选择";
            }else if($data["tab"][$k]["is_access"]==1){
                $data["tab"][$k]["type"]="仅员工可以选择";
            }else{
                $data["tab"][$k]["type"]="仅下游成员可以选择";
            }
        }
        $data["issue"]=db("crm_subregion_sys")->where("subregion_id=$subregion_id")->value("is_staff_issue");
        if(!$data["issue"])
            $data["issue"]=0;
        $data["issue2"]=db("crm_subregion_sys")->where("subregion_id=$subregion_id")->value("is_downstream_issue");
        if(!$data["issue2"])
            $data["issue2"]=0;
        //可发布动态
        $data["user2"]=db("crm_subregion_issue_staff")->alias("a")
        ->join("sh_crm_staff b","a.staff_id=b.staff_id")
        ->where("a.subregion_id=$subregion_id")
        ->field("a.staff_id,b.staff_name,head_img")
        ->select();
        $data["depart2"]=db("crm_subregion_issue_department")->alias("a")
        ->join("sh_crm_department b","a.department_id=b.department_id")
        ->where("a.subregion_id=$subregion_id")
        ->field("a.department_id,b.department_name")
        ->select();
        return $data;
    }
    public function getclass(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        try {
            $params = delToken($request->get());
            $subregion_id=$params["class_id"];
            //获取分类
            $data["subregion"]=db("crm_subregion")->where(["subregion_id"=>$subregion_id])->find();
            //获取系统和应用管理员
            $data["manage"]=$this->getManage();
            //获取普通管理员
            $data["man"]=db("crm_staff")->alias("a")
            ->join("sh_crm_subregion_manager b","a.staff_id=b.staff_id")
            ->where(["a.is_downstream"=>1,"a.sys_custodian"=>0,"a.is_dynamic_manage"=>1,"a.is_dynamic"=>0,"b.subregion_id"=>$subregion_id])
            ->field("a.staff_id,a.staff_name")->select();
           
           
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function delclass(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        try {
            $params = delToken($request->get());
            $subregion_id=$params["class_id"];
            //删除分类
            db("crm_subregion")->where(["subregion_id"=>$subregion_id])->delete();
            //删除设置
            db("crm_subregion_sys")->where(["subregion_id"=>$subregion_id])->delete();
            //删除动态
            //删除附件
            $this->successTerminate($params);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function updateclass(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        try {
            $params = delToken($request->post());
            $data["subregion_name"]=trim($params["subregion_name"]);
            $subregion_id=$params["subregion_id"];
            if(!$data["subregion_name"])
                \exception("社区名称不能为空");
            $data["remark"]=trim($params["remark"]);
            $has=db("crm_subregion")->where("subregion_name='{$data["subregion_name"]}' and subregion_id<>$subregion_id")->find();
            if($has){
                \exception($data["subregion_name"]."分社区已存在");
            }else{
                db("crm_subregion")->where(["subregion_id"=>$subregion_id])->update($data);
                db("crm_subregion_manager")->where(["subregion_id"=>$subregion_id])->delete();
                if($params["manlist"]){
                    $manlist=explode(',',$params["manlist"]);
                    $dataman=[];
                    foreach ($manlist as $k => $v) {
                        # code...
                        $tmp["subregion_id"]=$subregion_id;
                        $tmp["staff_id"]=$v;
                        $dataman[]=$tmp;
                    }
                    db("crm_subregion_manager")->insertAll($dataman);
                }
            }
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function addclass(Request $request){
        $StaffModel = new \app\crm\model\Staff();

        try {
            $params = delToken($request->post());
            $data["subregion_name"]=trim($params["subregion_name"]);
            if(!$data["subregion_name"])
                \exception("社区名称不能为空");
            $data["remark"]=trim($params["remark"]);
            if($params["value"]=="自定义员工可见范围")
                $staff_type=1;
            else
                $staff_type=0;
            if($params["value1"]=="自定义下游成员可见范围")
                $down_type=2;
            else if($params["value1"]=="仅通过审核后的下游成员可见")
                $down_type=1;
            else
                $down_type=0;
            $has=db("crm_subregion")->where(["subregion_name"=>$data["subregion_name"]])->find();
            if($has){
                \exception($data["subregion_name"]."分社区已存在");
            }else{
                $subregion_id=db("crm_subregion")->insertGetId($data);
                db("crm_subregion_sys")->insert(["subregion_id"=>$subregion_id,"is_staff_all_visible"=>$staff_type,"is_downstream_all_visible"=>$down_type]);
                if($params["manlist"]){
                    $manlist=explode(',',$params["manlist"]);
                    $dataman=[];
                    foreach ($manlist as $k => $v) {
                        # code...
                        $tmp["subregion_id"]=$subregion_id;
                        $tmp["staff_id"]=$v;
                        $dataman[]=$tmp;
                    }
                    db("crm_subregion_manager")->insertAll($dataman);
                }
            }

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
      /**
     * 员工简单列表接口
     */
    public function easy(Request $request){
        $StaffModel = new \app\crm\model\Staff();

        try {
            $params = delToken($request->get());
            $ids=db("crm_staff")->where(["is_downstream"=>1,"sys_custodian"=>0,"is_dynamic_manage"=>1,"is_dynamic"=>0])->column("staff_id");
            foreach ($ids as $k => $v) {
                # code...
                $ids[$k]="'{$ids[$k]}'";
            }
            $ids=implode(',',$ids);
            $data = $StaffModel->easySearch3($params,$ids);

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function getManage(){
        $model=new CusareaModel();
        $sys=db("crm_staff")->where(["is_downstream"=>1,"sys_custodian"=>1])->field("staff_id,staff_name")->select();
        $member=[];
        foreach ($sys as $key => $value) {
            # code...
            $sys[$key]["type"]="系统管理员";
            $member[]=$sys[$key];
        }
        $app=db("crm_staff")->where(["is_downstream"=>1,"sys_custodian"=>0,"is_dynamic_manage"=>0])->field("staff_id,staff_name")->select();
        foreach ($app as $key => $value) {
            # code...
            $app[$key]["type"]="应用管理员";
            $member[]=$app[$key];
        }
        
        return $member;
    }
    public function listSubregion(Request $request){
        $model=new CusareaModel();
        $data=db("crm_subregion")->alias("a")->join("sh_crm_subregion_sys b","a.subregion_id=b.subregion_id")
        ->field("a.subregion_id,a.subregion_name,b.is_staff_all_visible,b.is_downstream_all_visible")->select();
        foreach ($data as $k => $v) {
            # code...
            if($v["is_staff_all_visible"]==0){
                $data[$k]["staff_type"]="所有员工可见";
            }else{
                $data[$k]["staff_type"]="自定义员工可见范围可见";
            }
            if($v["is_downstream_all_visible"]==0){
                $data[$k]["down_type"]="所有下游成员可见";
            }else if($v["is_downstream_all_visible"]==1){
                $data[$k]["down_type"]="仅通过审核后的下游成员可见";
            }else{
                $data[$k]["down_type"]="自定义下游成员可见范围可见";
            }
        }
        return $data;
    }
    public function touser(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $has=db("crm_staff")->where("is_downstream=1 and (is_dynamic_manage=0 or is_dynamic=0) and staff_id='$staff_id'")->find();
            $c=$this->getnum();
            if(!$has){
                if($c>=10){
                    \exception("可使用当前应用的人数上限为10");
                }else{
                    db("crm_staff")->where(["staff_id"=>$staff_id])->update(["is_dynamic"=>0]);
                    $c++;
                }
            }
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function reuser(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $has=db("crm_staff")->where("is_downstream=1 and (is_dynamic_manage=0 or is_dynamic=0) and staff_id='$staff_id'")->find();
            $c=$this->getnum();
            if($has){
                db("crm_staff")->where(["staff_id"=>$staff_id])->update(["is_dynamic_manage"=>1,"is_dynamic"=>1]);
                $c--;
            }
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function tomanager(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $has=db("crm_staff")->where("is_downstream=1 and (is_dynamic_manage=0 or is_dynamic=0) and staff_id='$staff_id'")->find();
              $c=$this->getnum();
            if($has){
                db("crm_staff")->where(["staff_id"=>$staff_id])->update(["is_dynamic_manage"=>0,"is_dynamic"=>0]);
            }else{
              
                if($c>=10){
                    \exception("可使用当前应用的人数上限为10");
                }else{
                    db("crm_staff")->where(["staff_id"=>$staff_id])->update(["is_dynamic_manage"=>0,"is_dynamic"=>0]);
                    $c++;
                }
            }
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
        
    }
    public function remanager(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $c=db("crm_staff")->where(["staff_id"=>$staff_id])->update(["is_dynamic_manage"=>1]);
            $c=$this->getnum();
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function getnum(){
         $model=new CusareaModel();
        $c=db("crm_staff")->where("is_downstream=1 and (is_dynamic_manage=0 or is_dynamic=0)")->count();
        if(!$c){
            $c=0;
        }
        return $c;
               
    }
     /**
     * 部门列表接口
     */
    public function all(Request $request){
        $model=new CusareaModel();
        $params = delToken($request->get());
        $query=trim($params["query"]);
                if(!$query){
                   $dep=db("crm_department")->field('department_id, department_name as title, parent_id')
                        ->where('is_delete', 0)->select();
                     $where="is_downstream=1";
                }else{
                    $dep=[];
                     $where="staff_name like '%{$query}%' or phone like '%{$query}%' and is_downstream=1 ";
                }
     
       
        $sta=db("crm_staff")->field("staff_id,staff_name as title,department_id as parent_id")->where($where)->select();
        $manager=db("crm_staff")->where("is_downstream=1 and is_dynamic_manage=0")->column("staff_id");
        $user=db("crm_staff")->where("is_downstream=1 and is_dynamic=0")->column("staff_id");
        $all=[];
        foreach ($dep as $k => $v) {
            $dep[$k]["is_dep"]=1;
            $dep[$k]["is_disable"]=true;
            $dep[$k]["is_disable1"]=true;
            $dep[$k]["is_checked"]=false;
            $dep[$k]["is_checked1"]=false;
            $all[]=$dep[$k];
        }
        foreach ($sta as $k => $v) {
            # code...
            $sta[$k]["is_dep"]=0;
            $sta[$k]["department_id"]=-999;
            $sta[$k]["is_disable"]=false;
            $sta[$k]["is_disable1"]=false;
           
            if(in_array($v["staff_id"],$manager)){
                $sta[$k]["is_checked"]=true;
                $sta[$k]["is_checked1"]=true;
            }else if(in_array($v["staff_id"],$user)){
                $sta[$k]["is_checked"]=true;
                $sta[$k]["is_checked1"]=false;
            }else{
                 $sta[$k]["is_checked"]=false;
                $sta[$k]["is_checked1"]=false;
            }
            if($query){
                $sta[$k]["children"]=[];
            }
            $all[]=$sta[$k];
        }
        if(!$query){
            $all= $this->tree($all, 0);
        }
        return $all;
    }
     /**
     * 允许限制级数
     * @param $categories
     * @param int $pid
     * @param int $levelLimit
     * @param int $level
     * @return array
     */
    private function tree($categories, $pid = 0, $levelLimit = 0, $level = 1)
    {
        $children = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] === $pid) {

                if ($levelLimit === 0 || $level < $levelLimit) {
                    $category['is_show'] = false;
                    $category['children'] = $this->tree($categories, $category['department_id'], $levelLimit, $level + 1);
                }

                $children[] = $category;
            }
        }
        return $children;
    }
}
